package com.baidu.sggc.third.mb.model;

import com.baidu.sggc.third.mb.model.ProjectListRespDto.Project;
import com.baidu.sggc.core.common.utils.TokenUtils;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;


@Component
public class MbProjectApi {


  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private TokenUtils tokenUtils;




  @Value("${third.mb.projectListApi}")
  private String projectListApi;


  public List<Project> queryProjectList() {
    RestTemplate restTemplate = new RestTemplate();
    // 构建查询参数

    // 设置查询参数
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(projectListApi)
        .queryParam("pageSize", Integer.MAX_VALUE)
        .queryParam("pageNo", 1);

    String url = builder.buildAndExpand(new HashMap<>()).toUriString();
    // 构建请求实体
    HttpHeaders headers = tokenUtils.getHeaders(url , "");
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<?> entity = new HttpEntity<>(headers);

    // 发送GET请求
    ResponseEntity<ProjectListRespDto> response = restTemplate.exchange(url
        ,
        HttpMethod.GET,
        entity,
        ProjectListRespDto.class
    );

    // 处理响应
    if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
      System.out.println("Request failed with status code: " + response.getStatusCode());
      throw new RuntimeException("Request failed with status code: " + response.getStatusCode());
    }

    return response.getBody().getPage().getResult();
  }

}
